﻿
using WatchDog;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using WatchDog.Core;

namespace WatchDog.WinService
{
    public partial class Service1 : ServiceBase
    {
        private readonly System.Timers.Timer _timer;

        public Service1()
        {
            InitializeComponent();

            string strAssemblyFilePath = Assembly.GetExecutingAssembly().Location;
            string strAssemblyDirPath = Path.GetDirectoryName(strAssemblyFilePath);

            Log.Logger = new LoggerConfiguration()
                .WriteTo.File(strAssemblyDirPath + "/Logs/.log",
                rollingInterval: RollingInterval.Day,
                retainedFileTimeLimit: TimeSpan.FromDays(7),
                fileSizeLimitBytes: 5242880)
                .CreateLogger();

            var service = new FileService();

            _timer = new System.Timers.Timer(1000 * 30) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) =>
            {
                Log.Logger.Information($"Timers");

                try
                {
                    foreach (var item in service.GetFileInfo())
                    {
                        if(item.AutoStart == true)
                        {
                            if (ProcessHelper.IsStarting(item.FilePath))
                            {
                                Log.Logger.Information($"程序{item.FileName},{item.FilePath}正在运行中...");
                            }
                            else
                            {
                                Log.Logger.Information($"程序{item.FileName},{item.FilePath}未运行，准备启动...");
                                ProcessHelper.Starting(item.FilePath);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Logger.Error(ex,"执行定时任务时发生错误");
                }
                
            };
        }

        protected override void OnStart(string[] args)
        {
            Log.Logger.Information("启动服务");
            _timer.Start();
        }

        protected override void OnStop()
        {
            Log.Logger.Information("停止服务");
            _timer.Stop();
        }

        //private static bool IsStarting(WatchDog.FileInfo file)
        //{
        //    try
        //    {
        //        Log.Logger.Information("正在获取进程"+file.FileName);

        //        //var directory = Path.GetDirectoryName(file.FilePath);
        //        var process = Process.GetProcessesByName(file.FileName.Substring(0,file.FileName.Length-4));

        //        foreach (var item in process)
        //        {
        //            Log.Logger.Information("process "+item.ProcessName + "-" +item.MainModule.FileName.ToString() + "-" + file.FileName);
        //        }
      
        //        return process.Any(c => c.MainModule.FileName == file.FilePath);
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Logger.Error(ex,"获取程序运行状态出错："+file.FileName);
        //        return false;
        //    }
        //}

        //private static void Starting(string appPath)
        //{
        //    try
        //    {
        //        var proc = new Process();
        //        proc.StartInfo.FileName = appPath;
        //        proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(appPath);
        //        proc.Start();
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Logger.Error(ex, "启动程序出错:" + appPath);
        //    }
        //}
    }
}
